%%%-------------------------------------------------------------------
%%% File    : p7.erl
%%% Author  :  Plamen Dragozov <plamen at dragozov.com>
%%% Description : 
%%% By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6^(th) prime is 13.
%%% What is the 10001^(st) prime number?
%%%
%%% Created :  2 Dec 2008
%%%-------------------------------------------------------------------
-module(p7).

%% API
-export([solution/1]).

%% API
%%====================================================================
%%--------------------------------------------------------------------
%% Function: solution(N) -> int()
%% Description: Returns the Nth prime number.
%%--------------------------------------------------------------------
solution(1) -> 2;
solution(N) ->
    prime(3, N - 1, [2]).

%%====================================================================
%% Internal functions
%%====================================================================
%Iterate through all primes decrementing Counter until 1 is reached.
prime(N, Counter, Acc) ->
    case is_prime(N, math:sqrt(N), Acc) of 
        true ->
            case Counter of
                1 ->
                    N;
                _ -> prime(N + 2, Counter - 1, Acc ++ [N])
            end;
        _ -> prime(N + 2, Counter, Acc)
    end.

%Test if divisible by one of the previous primes.
%The list of primes has to be sorted in ascending order.
%We only need to check bellow or equal to sqrt(N)
is_prime(_, _, []) -> true;
is_prime(N, Sqrt, [H|T]) ->
    case (H > Sqrt) of
        true -> true;
        _ -> (N rem H =/= 0) andalso is_prime(N, Sqrt, T)
    end.

